package com.zwz.mall.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.umeng.analytics.MobclickAgent;
import com.zwz.mall.R;
import com.zwz.mall.config.Config;
import com.zwz.mall.managers.AppManager;
import com.zwz.mall.managers.UserManager;
import com.zwz.mall.models.User;
import com.zwz.mall.utils.SPUtils;
import com.zwz.mall.utils.SerialUtils;
import com.zwz.mall.utils.TUtil;
import com.zwz.mall.utils.ToastUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.disposables.Disposable;


public abstract class BaseActivity<T extends BasePresenter, E extends BaseModel> extends AppCompatActivity
{
    public T mPresenter;
    public E mModel;
    public Context mContext;
    protected Activity mActivity;
    private SweetAlertDialog mLoadingDialog;
    private Unbinder bind;
    private HashSet<Disposable> mSubcribers;
    public User user;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        doBeforeSetcontentView();

        user = UserManager.getInstance ().getUser ();
        if (getLayoutId() == 0) {
            return;
        }
        setContentView(getLayoutId());
        mContext = this;

        bind = ButterKnife.bind(this);
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        if (mPresenter != null) {
            mPresenter.mContext = this;
        }
        this.initPresenter();
        setAndroidNativeLightStatusBar(true);
        this.initView();
        this.fillData();
        this.setListener();

        initPush();
    }

    private void initPush() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        ToastUtils.cancel ();
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterSubscribers();
        bind.unbind();
    }
    /**
     * 设置layout前配置
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void doBeforeSetcontentView() {
        if (isNeedHideKerboard()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//不自动弹出软键盘
        }
        // 把actvity放到application栈中管理
        AppManager.getAppManager().addActivity(this);
        // 无标题
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 默认着色状态栏
        SetStatusBarColor();

    }

    protected boolean isNeedHideKerboard() {
        return true;
    }

    /*********************子类实现*****************************/
    //获取布局文件
    public abstract int getLayoutId();

    //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
    public abstract void initPresenter();

    //初始化view
    public abstract void initView();

    //加载网络数据
    public abstract void fillData();

    //事件
    public abstract void setListener();

    /**
     * 设置状态栏高度
     *
     * @param statusBarHeight
     */
    public void setStatusBarHeight(View view, ViewGroup.LayoutParams layoutParams, int statusBarHeight) {
        layoutParams.height = statusBarHeight;
        view.setLayoutParams(layoutParams);
    }
    /**
     * 压缩图片大小
     *
     * @param path 图片的路径
     * @return
     */
    public Map decodeSampleBitmap(String path)
    {
        //refundPhoto是将要呈现图片的ImageView控件
        //        int targetW = refundPhoto.getWidth();
        //        int targetH = refundPhoto.getHeight();

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int photoW = options.outWidth;
        int photoH = options.outHeight;
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("width", photoW);
        hashMap.put("height", photoH);
        return hashMap;
    }
    /**
     * 状态栏字亮色
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void SetStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //windowTranslucentStatus、windowTranslucentNavigation，都可以触发LAYOUT_FULLSCREEN 、LAYOUT_STABLE
            //但是状态栏只会变成半透明，要设置全透明必须用FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS和setStatusBarColor，但是windowTranslucentStatus=true时不会生效。
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN: 使状态栏出现的时候，不会重新调整activity的高度，状态栏覆盖在activity之上。
            //SYSTEM_UI_FLAG_LAYOUT_STABLE: 让应用的主体内容占用系统状态栏的空间
            //这俩好像只能在代码里设置
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
    /**
     * 谷歌原生方式修改
     * 状态栏图标文字为黑色
     *
     * @param dark
     */
    protected void setAndroidNativeLightStatusBar(boolean dark) {
        View decor = getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return getResources().getDimensionPixelSize(resourceId);
        }
        /*
        // todo
        // dp互转px工具
        //默认为20dp
         */

        return 0;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 注册Rx订阅
     *
     * @param subscriber
     */
    protected void registerSubscriber(Disposable subscriber) {
        if (subscriber == null) {
            return;
        }

        if (mSubcribers == null) {
            mSubcribers = new HashSet<>();
        }

        mSubcribers.add(subscriber);
    }

    /**
     * 取消Rx订阅
     */
    protected void unregisterSubscribers() {
        if (mSubcribers == null) {
            return;
        }

        for (Disposable subscriber : mSubcribers) {
            if (subscriber != null) {
                subscriber.dispose();
            }
        }
        mSubcribers.clear();
        mSubcribers = null;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }
    //加载方式
    public void showLoadingDialog(String msg) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
            mLoadingDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.red_btn_bg_color));
            mLoadingDialog.setCancelable(false);
            mLoadingDialog.setTitleText(msg);
        }
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }
    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        ToastUtils.showShort(text);
    }

    public void back(View view){
        finish();
    }

    public void showErrorTip(String msg) {
        showShortToast(msg);
        finish();
    }
}
